package beans;

import java.sql.ResultSet;
import java.sql.SQLException;

import database.DBHelper;
import encrypt.MD5;

public class MemberBean {
	String id;
	String pass;
	String email;
	int role = 0;
	
	public String getId() { return id; }
	public String getPass() { return pass; }
	public String getEmail() { return email; }
	public int getRole() { return role; }
	
	public void setId(String _id) { id = _id; }
	public void setPass(String _pass) { pass = _pass; }
	public void setEmail(String _email) { email = _email; }
	public void setRole(int _role) {role = _role; }

	/*
	 * Default constructor
	 */
	public MemberBean() {}
	
	/*
	 * Constructor for authentication
	 */
	public MemberBean(String _id, String _pass) {
		id = _id;
		pass = _pass;
	}
	
	/*
	 * Constructor for Registration
	 */
	public MemberBean(String _id, String _pass, String _email) {
		id = _id;
		pass = _pass;
		email = _email;
	}
	
	/*
	 * Constructor for Change Role
	 */
	public MemberBean(String _id, int _role) {
		id = _id;
		role = _role;
	}
	
	/*
	 * Authentication Method
	 * Related to /Authentication servlet
	 */
	public boolean doAuth() {
		DBHelper db = new DBHelper();
		String encpass = MD5.encrypt(pass);
		
		try {
			ResultSet rset = db.getStmt().executeQuery("select pass from member where id = '"+id+"'");	
			rset.next();
			if(rset.getString("pass").equals(encpass)) {
				return true;
			} else {
				return false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			db.close();
		}
	}
	
	/*
	 * Registration Mehtod
	 * Related to /Register servlet
	 */
	public boolean doRegister() {
		String encpass = MD5.encrypt(pass);
		String query = "insert into member values('"+id+"', '"+encpass+"', '"+email+"')";
		DBHelper db = new DBHelper();
		
		try {
			db.getStmt().execute(query);
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			db.close();
		}
	}
	
	/*
	 * Change Role Method
	 * Related to /Chrole servlet
	 */
	public boolean chrole() {
		String query = "update member set role = " + role + " where id = '" + id + "'";
		DBHelper db = new DBHelper();
		
		try {
			db.getStmt().execute(query);
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			db.close();
		}
	}
	
	/*
	 * ID check Method (check repetition)
	 * Related to /Idcheck servlet
	 */
	public boolean idCheck() {
		DBHelper db = new DBHelper();
		String query = "select id from member where id = '"+id+"'";
		try {
			ResultSet rset = db.getStmt().executeQuery(query);
			return rset.next();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			db.close();
		}
	}
}
